package site.luojie.netty.rpc.server.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import site.luojie.netty.rpc.common.UserService;
import site.luojie.netty.rpc.common.pojo.User;
import site.luojie.netty.rpc.server.codec.NettyRpcServerDecoder;
import site.luojie.netty.rpc.server.codec.NettyRpcServerEncoder;
import site.luojie.netty.rpc.server.handler.UserServerHandler;

/**
 * @author jie.luo
 * @since 2020-07-06 23:33
 **/
public class UserServiceImpl implements UserService {

    @Override
    public String sayHello(String param) {
        System.out.println("sayHello-----接收到客户端参数：" + param);
        return "你好：" + param;
    }

    @Override
    public String saveUser(User user) {
        System.out.println("saveUser-----接收到客户端参数：" + user);
        return "SUCCESS";
    }

    public static void startServer(String host, int port) throws InterruptedException {

        // 创建两个线程池
        // 处理连接
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // 处理读写操作
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        // 创建服务端启动组手
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 配置相关信息
        serverBootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer() {

                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        // 获取管道
                        ChannelPipeline pipeline = channel.pipeline();
                        // 添加数据编码解码
//                        pipeline.addLast(new StringEncoder());
//                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new NettyRpcServerDecoder());
                        pipeline.addLast(new NettyRpcServerEncoder());
                        // 添加UserServiceHandler
                        pipeline.addLast(new UserServerHandler());
                    }
                });

        // 绑定地址、端口
        serverBootstrap.bind(host, port).sync();

        System.out.println("server started");
    }
}
